import bcrypt from 'bcryptjs'
import { getUsers, addUser, updateUser, type StoredUser } from './database'

// 数据库用户相关类型定义
export type { StoredUser }

export interface AuthUser {
  id: string
  email: string
  name: string
  avatar?: string
  role: 'USER' | 'ADMIN'
}

export interface LoginCredentials {
  email: string
  password: string
}

export interface RegisterData {
  email: string
  password: string
  name: string
}

// 密码哈希
export async function hashPassword(password: string): Promise<string> {
  const saltRounds = 12
  return bcrypt.hash(password, saltRounds)
}

// 验证密码
export async function verifyPassword(password: string, hashedPassword: string): Promise<boolean> {
  return bcrypt.compare(password, hashedPassword)
}

// 生成JWT令牌
export function generateToken(user: AuthUser): string {
  return jwt.sign(
    {
      id: user.id,
      email: user.email,
      name: user.name,
      role: user.role
    },
    JWT_SECRET,
    { expiresIn: JWT_EXPIRES_IN }
  )
}

